import DataType from "@/utils/DataType";

const StringUtils = {
	//驼峰转下划线
	kebabCase(val) {
		let result = this.camelCase(val).replace(/([A-Z])/g, "-$1").toLowerCase();
		if (result.charAt(0) === "-") {
			result = result.slice(1);
		}
		return result;
	},
	//string 转 array
	toArray(val, separator) {
		return separator ? this.toString(val).split(separator) : this.toString(val).split("");
	},

	toString(val) {
		return DataType.isString(val) ? val : String.valueOf(val);
	},
	//首字母小写
	lowerFirst(val) {
		return this.toString(val).charAt(0).toLowerCase() + this.toString(val).slice(1);
	},
	//首字母大写
	upperFirst(val) {
		return this.toString(val).charAt(0).toUpperCase() + this.toString(val).slice(1);
	},
	//大写驼峰
	upperCamelCase(val) {
		return this.upperFirst(this.camelCase(val));
	},
	//大写单词组
	upperWordGroup(val) {
		return this.upperFirst(this.camelCase(val)).replace(/([A-Z])/g, " $1");
	},
	//下划线转驼峰
	camelCase(val) {
		let reg;
		if (this.toString(val).indexOf("-") !== -1) {
			reg = /-(\w)/g;
		} else if (this.toString(val).indexOf("_") !== -1) {
			reg = /_(\w)/g;
		} else if (this.toString(val).indexOf(" ") !== -1) {
			reg = / (\w)/g;
		}
		return this.toString(val).replace(reg, ($0, $1) => $1.toUpperCase());
	},
	//获取string中某一char下标
	findIndex(val, char) {
		return this.toString(val).indexOf(char);
	},
	//判断大写
	isUpperCase(char) {
		return /^[A-Z]+$/.test(char);
	},
	//判断小写
	isLowerCase(char) {
		return /^[a-z]+$/.test(char);
	},
	//判断字母
	isLetter(char) {
		return /^[a-zA-Z]+$/.test(char);
	},
	//截取字符串获取组件名称
	subString(value) {
		if (/index\.\w+$/.test(value)) {
			return this.camelCase(value.replace(/^\.\//, "").split("/")[0]);
		} else {
			return this.camelCase(value.split("/").pop().replace(/\.\w+$/, ""));
		}
	}
};

export default StringUtils;
